package com.pp.controller;

import com.pp.common.pojo.User;
import com.pp.common.vo.SysResult;
import com.pp.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

@RestController
@CrossOrigin
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 修改用户信息
     * @param user
     * @return
     */
    @PutMapping("/updateUser")
    public SysResult updateUser(@RequestBody User user){
        String newpassword = encodePwd().encode(user.getPassword());
        user.setPassword(newpassword);
        System.out.println(user.toString());
        userService.updateUser(user);

        return SysResult.success();
    }

    /**
     * 用户修改信息需要发起一次请求比对密码获取用户密码
     * @param user
     * @return
     */
    @PostMapping("/getPassword")
    public SysResult getPassword(@RequestBody User user){
        User paUser = userService.getPassword(user);
        if (encodePwd().matches(user.getPassword(),paUser.getPassword())){
            return SysResult.success();
        }else {
           return SysResult.fail();
        }
    }

    @GetMapping("/selectByName/{createdUser}")
    public SysResult seletctByName(@PathVariable String createdUser){
        System.out.println(createdUser);
        User user = userService.selectByName(createdUser);
        return SysResult.success(user);
    }

    /**
     * 基于用户id查询用户信息
     * @return
     */
    @GetMapping("/{id}")
    public SysResult selectUser(@PathVariable Integer id){
        User user = userService.selectUser(id);
        return SysResult.success(user);
    }

    public BCryptPasswordEncoder encodePwd(){
        return new BCryptPasswordEncoder();
    }
}
